<template>
	<view class="add-moment-page">
		<custom-navbar class="my-navigation" title="发布动态" :isReturnVisible="true" :isAddVisible="false" />

		<view class="form-container">
			<!-- 文字内容输入区 -->
			<view class="content-input">
				<textarea v-model="content" placeholder="分享你的新鲜事..." maxlength="200" auto-height></textarea>
			</view>

			<!-- 图片上传区 -->
			<view class="image-upload">
				<view class="image-container">
					<!-- 已上传图片预览 -->
					<view class="image-preview" v-for="(img, index) in images" :key="index">
						<image :src="img" mode="aspectFill"></image>
						<view class="delete-btn" @click="removeImage(index)">×</view>
					</view>

					<!-- 添加图片按钮 -->
					<view class="add-image-btn" @click="chooseImage" v-if="images.length < 9">
						<image src="/static/icons/add_image.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>

			<!-- 发布按钮 -->
			<view class="submit-btn">
				<button :disabled="publishing" @click="publishMoment">
					<text v-if="!publishing">发布</text>
					<text v-else>发布中...</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import CustomNavbar from '../../components/custom-navbar.vue';
	import {
		addMoment
	} from '../../api/moment';
	import {
		uploadFile,
		batchUploadFiles
	} from '../../api/file';

	const content = ref('');
	const images = ref([]);
	const publishing = ref(false);

	// 上传图片到服务器
	async function uploadImage(filePath) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: 'http://localhost:7000/elderly/file/upload',
				filePath: filePath,
				name: 'file',
				// header: {
				// 	'Content-Type': 'multipart/form-data'
				// },
				success: (res) => {
					if (res.statusCode === 200) {
						const data = JSON.parse(res.data);
						console.log(data);
						if (data && data.code === 1000) {
							resolve(data.data); // 返回图片URL
						} else {
							reject(new Error(data.msg || '上传失败'));
						}
					} else {
						reject(new Error(`上传失败，状态码: ${res.statusCode}`));
					}
				},
				fail: (err) => {
					reject(err);
				}
			});
		});
	}

	// 选择图片并上传
	function chooseImage() {
		uni.chooseImage({
			count: 9 - images.value.length,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success: async (res) => {
				const tempFilePaths = res.tempFilePaths;

				// 显示上传进度
				uni.showLoading({
					title: '上传中...',
					mask: true
				});

				try {
					// 批量上传图片
					const results = await batchUploadFiles(tempFilePaths);

					// 添加新上传的图片URL
					images.value = [...images.value, ...results];

					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '图片上传失败',
						icon: 'none'
					});
				}
			}
		});
	}

	// 移除图片
	function removeImage(index) {
		images.value.splice(index, 1);
	}

	// 发布动态
	async function publishMoment() {
		if (!content.value.trim() && images.value.length === 0) {
			uni.showToast({
				title: '请填写内容或添加图片',
				icon: 'none'
			});
			return;
		}
		publishing.value = true;
		try {
			// 调用API发布动态
			await addMoment({
				content: content.value,
				picUrlList: images.value
			});
			uni.showToast({
				title: '发布成功',
				icon: 'success'
			});
			// 清空内容
			content.value = '';
			images.value = [];
			publishing.value = false;
			// 返回前一个页面
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		} catch (error) {
			publishing.value = false;
			uni.showToast({
				title: error.message || '发布失败',
				icon: 'none'
			});
		}
	}
</script>

<style scoped>
	.add-moment-page {
		min-height: 100vh;
		background: url('@/static/background.png') no-repeat;
		/* background-size: cover; */
		padding-bottom: 20px;
		padding-top: 30px;
	}

	.my-navigation {
		margin-bottom: 60px;
		/* border: 1px solid; */
	}

	.form-container {
		padding: 20px;
		margin-top: 40px;
	}

	.content-input textarea {
		width: 100%;
		min-height: 300px;
		font-size: 16px;
		padding: 10px;
		background-color: #fff;
		border-radius: 8px;
		box-sizing: border-box;
		/* 添加明显的边框 */
		border: 1px solid #e0e0e0;
		/* 浅灰色边框 */
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		/* 轻微阴影增加层次感 */
	}

	.image-upload {
		margin-top: 20px;
	}

	.image-container {
		display: flex;
		flex-wrap: wrap;
		gap: 8px;
	}

	.image-preview {
		position: relative;
		width: 100px;
		height: 100px;
		border-radius: 8px;
		overflow: hidden;
		background-color: #f0f0f0;
	}

	.image-preview image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 24px;
		height: 24px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 0 0 0 8px;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 18px;
		z-index: 10;
	}

	.add-image-btn {
		width: 100px;
		height: 100px;
		border: 1px dashed #ccc;
		border-radius: 8px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
	}

	.add-image-btn image {
		width: 40px;
		height: 40px;
	}

	.submit-btn {
		margin-top: 30px;
	}

	.submit-btn button {
		background-color: #F6A031;
		color: white;
		border-radius: 50px;
		height: 45px;
		line-height: 45px;
		font-size: 16px;
	}

	.submit-btn button[disabled] {
		background-color: #cccccc;
	}
</style>